<template>
  <div class="myApi">
    <template v-if="tab === 'api'">
      <div class="create front-color">
        <h1>{{$t('user.api.newapi')}}</h1>
        <div class="create_rule">
          <P>{{$t('user.api.prompt1')}}<span class="look pointer" @click="seeDoc">{{$t('user.api.apidocd')}}</span>{{$t('user.api.prompt4')}}</P>
          <P>{{$t('user.api.prompt2')}}</P>
          <P>{{$t('user.api.prompt3')}}</P>
        </div>
        <div class="create_name">
          <div class="auto">
            <div class="verify" v-if="userinfo.isOpenMobileCheck === 0 && userinfo.googleStatus === 0">
              <div class="verify_text">{{$t('user.api.binding')}}</div>
              <div class="verify_btn"><router-link tag="button" to="/personal/bindMobile">{{$t('user.api.binding_phone')}}</router-link><router-link tag="button" to="/personal/googlebind">{{$t('user.api.binding_google')}}</router-link></div>
            </div>
            <div class="inp" v-if="userinfo.isOpenMobileCheck === 1 || userinfo.googleStatus === 1">
              <template v-for="(item,key,index) in apidata">
                <inline-input
                  :property = "item"
                  v-model = "item.value"
                  @onevents = "somethings">
                </inline-input>
              </template>
              <div class="createOption"><button v-show="confim" @click="submit()">{{$t('user.api.determine')}}</button></div>
            </div>
          </div>
        </div>
      </div>
      <div class="api_key front-color">
        <h1>{{$t('user.api.myApiKey')}}</h1>
        <div class="list">
          <div class="rel">
            <div class="loading" v-if="loadingShow">
              <loading></loading>
            </div>
            <table>
              <thead>
              <tr>
                <th>{{$t('user.api.ctime')}}</th>
                <th>{{$t('user.api.lable')}}</th>
                <th>{{$t('user.api.token')}}</th>
                <th>{{$t('user.api.api_addres')}}</th>
                <th>{{$t('user.api.key')}}</th>
                <th>{{$t('user.api.operation')}}</th>
              </tr>
              </thead>
              <tbody v-if="apiList">
              <tr v-for="(item, index) in apiList" :key="index">
                <td>{{item.ctime}}</td>
                <td>{{item.label}}</td>
                <td>{{item.token}}</td>
                <td>{{item.believeIps}}</td>
                <td @click="seeApi(item, index)" class="pointer">{{$t('user.api.see')}}</td>
                <td><span class="edit pointer" @click="modifyApi(item)">{{$t('user.api.upload')}}</span><span class="delete pointer" @click="dele(item)">{{$t('user.api.deletes')}}</span></td>
              </tr>
              </tbody>
            </table>
            <div class="noDataDiv" v-if="apiList === null">
              <div class="auto">
                <img src="../../assets/addImg/common/noData.png" alt="">
                <noData></noData>
              </div>
            </div>
          </div>
          <Vpagination v-if="(apition.count/apition.pageSize) > 1"
                       :total="apition.count"
                       :current-page='apition.page'
                       :display='apition.pageSize'
                       @pagechange="apitionechage($event)" class="page">
          </Vpagination>
        </div>
      </div>
    </template>
    <template v-if="tab === 'doc'">
      <div class="">
        <div class="quotes front-color">
          <h1>{{$t('user.api.apidocd')}}<span class="back pointer" @click="seeDoc">< {{$t('user.api.back')}}</span></h1>
          <p class="itemP"><span class="obvious">{{$t('user.api.quotation_api')}}</span> <span class="obviousDes">{{$t('user.api.quotation_describe')}}</span></p>
          <p class="doclist">
            <span class="interface">{{$t('user.api.interface')}}</span>
            <span class="describe">{{$t('user.api.describe')}}</span>
          </p>
          <p class="doclist" v-for="(item,index) in apidoc.quotation" :key="index">
            <span class="interface">{{item.interface}}</span>
            <span class="describe">{{item.describe}}</span>
          </p>
        </div>
        <div class="ex front-color">
          <p class="itemP"><span class="obvious">{{$t('user.api.transaction_api')}}</span><span class="obviousDes">{{$t('user.api.transaction_describe')}}</span></p>
          <p class="doclist">
            <span class="interface">{{$t('user.api.interface')}}</span>
            <span class="describe">{{$t('user.api.describe')}}</span>
          </p>
          <p class="doclist" v-for="(item,index) in apidoc.transaction" :key="index">
            <span class="interface">{{item.interface}}</span>
            <span class="describe">{{item.describe}}</span>
          </p>
        </div>
      </div>
    </template>
    <el-dialog :flag='isShow'
               :title='apiTitel'
               :width='450'
               :dialogClose='cole'>
      <div slot="content">
        <h4>{{cont}}</h4>
        <div class="qrcode" v-show="Qrcode" >
          <img :src="onapi.qrCode">
          <p>{{onapi.secretKey}}</p>
        </div>
        <template v-for="(item,key,index) in apidata">
          <inline-input
            :property = "item"
            v-model = "item.value"
            @onevents = "somethings">
          </inline-input>
        </template>
      </div>
      <div slot="options"><button v-show="rest" @click="reset()">{{$t('user.api.cancel')}}</button><button v-show="confim" @click="submit()">{{$t('user.api.determine')}}</button></div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import InlineInput from '@/components/common/inlineInput'
import loading from '../common/loadingModel'
import Vpagination from '@/components/common/pagination'
import elDialog from '../common/addCommon/dialog'
import noData from './common/noData'

export default {
  name: 'myApi',
  data () {
    return {
      tab: 'api',
      isShow: false,
      apiTitel: '', // 弹框标题
      apidata: '',  // input框集合
      cont: '',     // 弹框内容
      apiList: [],  // API列表数据
      rest: false,  // 是否显示取消按钮
      confim: true, // 是否显示确认按钮
      onapi: '',    // 单个api数据
      Qrcode: false,
      axiosUrl: '',
      apiType: '',
      msage: '',
      index: '',
      apition: {
        count: 0,
        pageSize: 10,
        page: 1
      },
      loadingShow: false,
      // 新建API
      newapi: {},
      //  查看api
      seeapi: {},
      // 修改api
      modify: {},
      apidoc: {} // api文档数据
    }
  },
  components: { loading, Vpagination, noData, elDialog, InlineInput },
  mounted () {
    this.newapi = this.newapi_obj
    this.seeapi = this.seeapi_obj
    this.modify = this.modify_obj
    this.apidoc = this.apidoc_obj
    this.loading()
    this.newly()
  },
  watch: {
    'newapi_obj' (val) {
      this.newapi = val
    },
    'seeapi_obj' (val) {
      this.seeapi = val
    },
    'modify_obj' (val) {
      this.modify = val
    },
    'apidoc_obj' (val) {
      this.apidoc = val
    },
    'userinfo' (val) {
      val && this.newly()
    }
  },
  computed: {
    ...mapState({
      userinfo ({baseData: {_user}}) {
        return _user || false
      }
    }),
    // 新建api
    newapi_obj () {
      return {
        // 备注名
        label: {
          // title: this.$t('user.api.memo'),
          title: '',
          formType: 'text',
          name: 'label',
          value: '',
          placeholder: this.$t('user.api.memo_holder')
        },
        // api地址
        believeIps: {
          // title: this.$t('user.api.api_addres'),
          title: '',
          formType: 'text',
          name: 'believeIps	',
          value: '',
          placeholder: this.$t('user.api.api_addres_holder')
        },
        // 短信验证码
        smsValidCode: {
          // title: this.$t('user.api.validCode'),
          title: '',
          formType: 'verifiCode',
          name: 'smsValidCode',
          payload: 'phoneNumber',
          operationType: 16,
          startTime: false,
          value: '',
          placeholder: this.$t('user.api.validCode_holder')
        },
        // 谷歌验证证
        googleCode: {
          // title: this.$t('user.api.googleCode'),
          title: '',
          formType: 'text',
          name: 'googleCode',
          value: '',
          placeholder: this.$t('user.api.googleCode_holder')
        }
      }
    },
    // 查看api
    seeapi_obj () {
      return {
        smsValidCode: {
          // title: this.$t('user.api.validCode'),
          title: '',
          formType: 'verifiCode',
          name: 'smsValidCode',
          payload: 'phoneNumber',
          operationType: 16,
          startTime: false,
          value: '',
          placeholder: this.$t('user.api.validCode_holder')
        },
        // 谷歌验证证
        googleCode: {
          // title: this.$t('user.api.googleCode'),
          title: '',
          formType: 'text',
          name: 'googleCode',
          value: '',
          placeholder: this.$t('user.api.googleCode_holder')
        }
      }
    },
    // 修改api
    modify_obj () {
      return {
        // 备注名
        label: {
          // title: this.$t('user.api.memo'),
          title: '',
          formType: 'text',
          name: 'label',
          value: '',
          placeholder: this.$t('user.api.memo_holder')
        },
        // api地址
        believeIps: {
          // title: this.$t('user.api.api_addres'),
          title: '',
          formType: 'text',
          name: 'believeIps	',
          value: '',
          placeholder: this.$t('user.api.api_addres_holder')
        },
        // 短信验证码
        smsValidCode: {
          // title: this.$t('user.api.validCode'),
          title: '',
          formType: 'verifiCode',
          name: 'smsValidCode',
          payload: 'phoneNumber',
          operationType: 16,
          startTime: false,
          value: '',
          placeholder: this.$t('user.api.validCode_holder')
        },
        // 谷歌验证证
        googleCode: {
          // title: this.$t('user.api.googleCode'),
          title: '',
          formType: 'text',
          name: 'googleCode',
          value: '',
          placeholder: this.$t('user.api.googleCode_holder')
        }
      }
    },
    apidoc_obj () {
      return {
        quotation: [
          {
            'interface': '/open/api/get_records',
            'describe': this.$t('user.api.apidoc.K_line')
          },
          {
            'interface': '/open/api/get_ticker',
            'describe': this.$t('user.api.apidoc.transaction')
          },
          {
            'interface': '/open/api/get_trades',
            'describe': this.$t('user.api.apidoc.depth')
          },
          {
            'interface': '/open/api/market_dept',
            'describe': this.$t('user.api.apidoc.delegate')
          }
        ],
        transaction: [
          {
            'interface': '/open/api/all_order',
            'describe': this.$t('user.api.apidoc.delegate')
          },
          {
            'interface': '/open/api/all_trade',
            'describe': this.$t('user.api.apidoc.records')
          },
          {
            'interface': '/open/api/cancel_order',
            'describe': this.$t('user.api.apidoc.entrustment')
          },
          {
            'interface': '/open/api/common/symbols',
            'describe': this.$t('user.api.apidoc.query')
          },
          {
            'interface': '/open/api/create_order',
            'describe': this.$t('user.api.apidoc.create_order')
          },
          {
            'interface': '/open/api/market',
            'describe': this.$t('user.api.apidoc.latest_transaction_price')
          },
          {
            'interface': '/open/api/new_order',
            'describe': this.$t('user.api.apidoc.current_entrustment')
          },
          {
            'interface': '/open/api/order_info',
            'describe': this.$t('user.api.apidoc.get_details_order')
          },
          {
            'interface': '/open/api/user/account',
            'describe': this.$t('user.api.apidoc.balance')
          }
        ]
      }
    }
  },
  methods: {
    loading () {
      let _this = this
      this.loadingShow = true
      setTimeout(function () {
        _this.getapi()
      }, 500)
    },
    Projectile (inp, dis, title, ret, content, qr, fim) {
      this.apidata = inp      // 表单
      this.isShow = dis       // 控制弹框显示
      this.apiTitel = title   // 弹框标题
      this.rest = ret         // 取消按钮
      this.cont = content     // 内容
      this.Qrcode = qr        // 图片
      this.confim = fim       // 确认按钮
    },
    // 关闭弹框
    cole () {
      this.isShow = false
      this.eliminate()
      this.newly()
    },
    // 发送验证码
    somethings (v) {
      if (v.handleType === 'sendCode') {
        this.sendVerify(v)
      }
    },
    sendVerify (item) {
      let data = {}
      data.operationType = this.apidata[item.name].operationType
      this.apidata[item.name].startTime = true // 开启倒计时
      this.commonHttp.smsValidCode(data).then((data) => {
        if (data.code === '0') {
        }
      })
    },
    //  新建Api
    newly () {
      if (this.userinfo.googleStatus === 1 && this.userinfo.isOpenMobileCheck === 1) {
        this.Projectile(this.newapi, false, '', false, '', false, true)
      } else if (this.userinfo.isOpenMobileCheck === 1 && this.userinfo.googleStatus === 0) {
        delete this.newapi.googleCode
        this.Projectile(this.newapi, false, '', false, '', false, true)
      } else if (this.userinfo.isOpenMobileCheck === 0 && this.userinfo.googleStatus === 1) {
        delete this.newapi.smsValidCode
        this.Projectile(this.newapi, false, '', false, '', false, true)
      }
      this.eliminate()
      this.axiosUrl = this.$store.state.url.personal.create_open_api
      this.apiType = 1
      this.getapi()
    },
    // 查看api
    seeApi (v) {
      if (this.userinfo.googleStatus === 1 && this.userinfo.isOpenMobileCheck === 1) {
        this.Projectile(this.seeapi, true, this.$t('user.api.see_api'), true, '', false, true)
      } else if (this.userinfo.isOpenMobileCheck === 1 && this.userinfo.googleStatus === 0) {
        delete this.seeapi.googleCode
      } else if (this.userinfo.isOpenMobileCheck === 0 && this.userinfo.googleStatus === 1) {
        delete this.seeapi.smsValidCode
      }
      this.Projectile(this.seeapi, true, this.$t('user.api.see_api'), true, '', false, true)
      this.eliminate()
      this.msage = v.token
      this.axiosUrl = this.$store.state.url.personal.open_api_on
      this.apiType = 2
    },
    // 修改api
    modifyApi (data) {
      this.modify.label.value = data.label
      this.modify.believeIps.value = data.believeIps
      this.axiosUrl = this.$store.state.url.personal.update_api
      if (this.userinfo.googleStatus === 1 && this.userinfo.isOpenMobileCheck === 1) {
        this.Projectile(this.modify, true, this.$t('user.api.update'), true, '', false, true)
      } else if (this.userinfo.isOpenMobileCheck === 1 && this.userinfo.googleStatus === 0) {
        delete this.modify.googleCode
      } else if (this.userinfo.isOpenMobileCheck === 0 && this.userinfo.googleStatus === 1) {
        delete this.modify.smsValidCode
      }
      this.Projectile(this.modify, true, this.$t('user.api.update'), true, '', false, true)
      this.apiType = 3
      this.msage = data.token
    },
    // 删除
    dele (v, i) { // this.$t('user.questions.ques_prompt')
      this.Projectile('', true, '', true, this.$t('user.api.delete'), false, true)
      this.axiosUrl = this.$store.state.url.personal.delete_open_api
      this.apiType = 4
      this.msage = v.token
      this.index = i
    },
    qrcode () {
      console.log('qrcode')
      this.Projectile('', true, this.$t('user.order.trans_account.details'), true, '', true, false)
    },
    // 取消
    reset () {
      this.isShow = false
      this.newly()
    },
    // 清除input内容
    eliminate () {
      for (let item in this.apidata) {
        if (this.apidata[item].value) {
          this.apidata[item].value = ''
        }
      }
    },
    submit () {
      let data = {}
      // 获取时间戳
      data.time = new Date().getTime()
      let fla = true
      for (let item in this.apidata) {
        if (item !== 'believeIps') {
          if (!this.apidata[item].value || this.apidata[item].value === '') {
            this.$set(this.apidata[item], 'errorInfo', this.$t('user.api.please_enter') + this.apidata[item].title)
            fla = false
          }
        }
        data[item] = this.apidata[item].value
      }
      if (!fla) return false
      if (this.apiType === 2) {
        data.token = this.msage
      }
      if (this.apiType === 4) {
        data.token = this.msage
      }
      if (this.apiType === 3) {
        data.token = this.msage
      }
      this.axios({
        url: this.axiosUrl,
        params: data,
        method: 'post'
      }).then((data) => {
        switch (this.apiType) {
          case 1:
            if (data.code === '0') {
              this.$store.dispatch('setTipState', this.$t('user.api.new_success'))
            } else {
              this.$store.dispatch('setTipState', {text: data.msg, type: 'error'})
            }
            this.newly()
            break
          case 2:
            if (data.code === '0') {
              this.onapi = data.data
              this.qrcode()
            } else {
              this.newly()
              this.$store.dispatch('setTipState', {text: data.msg, type: 'error'})
            }
            break
          case 4:
            if (data.code === '0') {
              this.$store.dispatch('setTipState', this.$t('user.questions.delete_succ'))
              this.apiList.splice(this.index, 1)
            } else {
              this.$store.dispatch('setTipState', {text: data.msg, type: 'error'})
            }
            this.newly()
            break
          default:
            if (data.code === '0') {
              this.$store.dispatch('setTipState', this.$t('user.api.updata_success'))
            } else {
              this.$store.dispatch('setTipState', {text: data.msg, type: 'error'})
            }
            this.newly()
            break
        }
      })
      this.isShow = false
      this.modify.smsValidCode && (this.modify.smsValidCode.value = '')
      this.modify.googleCode && (this.modify.googleCode.value = '')
      this.eliminate()
    },
    getapi () {
      this.axios({
        url: this.$store.state.url.personal.my_api_list,
        headers: {},
        params: {
          page: this.apition.page,
          pageSize: this.apition.pageSize
        },
        method: 'post'
      }).then((data) => {
        if (data.code === '0') {
          this.loadingShow = false
          this.apiList = data.data.apiList
          this.apiList && this.apiList.forEach(item => {
            item.ctime = this._P.formatTime(item.ctime)
          })
          this.apition.count = data.data.count
        } else {
          this.$store.dispatch('setTipState', {text: data.msg, type: 'error'})
        }
      })
    },
    apitionechage (i) {
      this.loadingShow = true
      this.apition.page = i
      let _this = this
      setTimeout(function () {
        _this.getapi()
      }, 500)
    },
    // api文档
    seeDoc () {
      if (this.tab === 'api') {
        this.tab = 'doc'
        return false
      } else if (this.tab === 'doc') {
        this.tab = 'api'
      }
    }
  }
}
</script>
